<template>
  <div style="position: relative">
    <div class="search">
      <van-search v-model="value" show-action placeholder="请输入搜索关键词" @search="searchResultAxios">
        <template #action>
          <div class="searchBtn" @click="searchResultAxios">搜索</div>
        </template>
      </van-search>
    </div>

    <div class="searchRelated">
      <div>
        <b>搜索历史</b>
        <div class="iconfont delete" @click="historyDelete">&#xe8b6;</div>

        <span
          v-for="(item, index) in searchHistory"
          :key="index"
          @click="historyClick(item.name)"
        >
          {{ item.name }}
        </span>
      </div>

      <div>
        <b>热门搜索</b>

        <span
          v-for="(item, index) in searchHot"
          :key="index"
          @click="historyClick(item.name)"
        >
          {{ item.name }}
        </span>
      </div>
    </div>

    <div class="recommend">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div class="recommendValueBox">
          <Recommend
            v-for="item in searchResultData"
            :key="item.id"
            :data="item"
          >
          </Recommend>
        </div>
      </van-list>
    </div>
  </div>
</template>

<script>
import { searchResult } from "@/api/search.js";
import Recommend from "@/components/recommend.vue";
export default {
  data() {
    return {
      searchResultData: [],
      searchHistory: [],
      searchHot: [
        { name: "iphone6" },
        { name: "iphone12" },
        { name: "笔记本电脑" },
        { name: "游戏本" },
        { name: "乐淘大优惠" },
      ],

      pagesize: 10,
      pageindex: 1,
      value: "",

      loading: false,
      // finished设为true是为了在还没搜索的时候让上拉加载不执行
      finished: true,
    };
  },
  methods: {
    // 点击搜索获取数据(历史搜索)
    async searchResultAxios() {
      // 点击搜索按钮获取数据

      this.pageindex = 1;

      let { data } = await searchResult(
        this.value,
        this.pagesize,
        this.pageindex
      );

      this.searchResultData = data;
      // 设为false,让上拉加载可执行
      this.finished = false;

      // 判断数据是否已加载完毕,已加载完毕就让上拉加载不可执行
      if (data.length < 10) {
        this.finished = true;
      }

      // 1.历史搜索 2.判断历史数据是否跟本地存储重复

      var historyData = JSON.parse(localStorage.getItem("history"));

      // 如果本地存储没数据,就直接存入数据, 一开始没数据的时候for循环执行不了
      if (historyData == null || historyData == "") {
        this.searchHistory.unshift({ name: this.value });
        localStorage.setItem("history", JSON.stringify(this.searchHistory));
      } else {
        // 用for循环判断本地存储的数据是否跟当前input框内容重复
        for (let i = 0; i < this.searchHistory.length; i++) {
          // 如果重复,直接终止代码执行, 终止后就不会执行下面那一行的添加操作
          if (this.searchHistory[i].name == this.value) {
            return;
          }
        }

        // 添加数据操作
        this.searchHistory.unshift({ name: this.value });
        localStorage.setItem("history", JSON.stringify(this.searchHistory));
      }
    },
    // 搜索历史点击事件
    historyClick(name) {
      this.value = name;
      // 调用点击搜索按钮事件
      this.searchResultAxios();
    },
    historyDelete() {
      // Dialog原来是这样调用Dialog组件,不过因为他的特殊性,得改成this.$dialog
      this.$dialog
        .confirm({
          title: "删除",
          message: "确认删除历史搜索记录吗?",
        })
        .then(() => {
          this.searchHistory = []
          localStorage.removeItem("history") 
        })
        .catch(() => {});
    },
    // 上拉加载更多数据
    async searchResultPush(pageindex) {
      let { data } = await searchResult(this.value, this.pagesize, pageindex);

      this.searchResultData.push(...data);

      // 判断是否还有数据,如果没有就把finished设为true,也就是让页面的底部显示"没有更多了"
      if (data.length < 10) {
        this.finished = true;
      }
    },

    // onLoad上拉加载时触发的函数
    onLoad() {
      setTimeout(() => {
        // 上拉加载
        if (this.loading == true) {
          this.pageindex++;
          this.searchResultPush(this.pageindex);
        }

        this.loading = false;
      }, 600);
    },
  },

  created() {
    // 页面加载完从本地存储获取数据渲染
    var historyData = JSON.parse(localStorage.getItem("history"));
    // 如果没有数据,就得给searchHistory赋值个数组, 因为当本地存储没数据时,赋给searchHistory的值是null,后续的unshift操作会报错
    if (historyData == null || historyData == "") {
      this.searchHistory = [];
    } else {
      this.searchHistory = historyData;
    }
  },

  components: {
    Recommend,
  },
};
</script>

<style lang="scss" scoped>
$ui-width: 720;
$num: 15;
$baseFontSize: 50; // 750 / 15
@function px2rem($px) {
  @return $px / $baseFontSize + rem;
}

@font-face {
  font-family: "iconfont"; /* Project id 2637818 */
  src: url("//at.alicdn.com/t/font_2637818_t2ie7lju9ug.woff2?t=1638190870426")
      format("woff2"),
    url("//at.alicdn.com/t/font_2637818_t2ie7lju9ug.woff?t=1638190870426")
      format("woff"),
    url("//at.alicdn.com/t/font_2637818_t2ie7lju9ug.ttf?t=1638190870426")
      format("truetype");
}
.iconfont {
  font-family: "iconfont" !important;
  font-size: 24px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -webkit-text-stroke-width: 0.2px;
  -moz-osx-font-smoothing: grayscale;
}

.search {
  width: 70%;
  font-size: px2rem(16);
  // border: 2px solid black;
  text-align: center;
  position: absolute;
  top: -50px;
  left: 50%;
  transform: translateX(-50%);

  .searchBtn {
    padding: 0 10px;
    background-color: #f7be2c;
    color: white;
  }
}

.searchRelated {
  padding: 16px 0;
  font-size: px2rem(19);
  div {
    position: relative;
    margin-bottom: 50px;
    b {
      display: block;
      margin: 8px 0;
    }
    span {
      color: #5e5757;
      display: inline-block;
      border-radius: 8px;
      margin: 5px 4px;
      font-size: px2rem(16);
      background-color: #f3f5f6;
      padding: 4px 8px;
      cursor: pointer;
    }
    .delete {
      position: absolute;
      cursor: pointer;
      top: 0;
      right: 30px;
    }
  }
}

.recommend {
  padding: 15px 10px;
  background-color: #f0f0f0;
  position: relative;

  .recommendFont {
    width: 100px;
    background-color: #f0f0f0;
    text-align: center;
    z-index: 1;
    position: relative;
    display: block;
    font-size: px2rem(16);
    margin: auto;
  }

  hr {
    position: absolute;
    top: 0;
    left: 5%;
    width: 90%;
  }

  .recommendValueBox {
    margin-top: 20px;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    span {
      font-size: px2rem(14);
    }
    .remai {
      width: 50%;
    }
  }
}
</style>